//
//  ViewController.m
//  享动
//
//  Created by 沈浩hh on 16/4/5.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "ViewController.h"
#import "MessageCollectionViewCell.h"
#import "Message1TableViewController.h"
#import "Message2TableViewController.h"
#import "ScrollViewModel.h"
#import "LBView.h"
#import "GameViewController.h"

@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
// 标识
@property (nonatomic, strong) UIView *moveView;
// 装载collectionView的title
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) Message1TableViewController *message1Vc;

@property (nonatomic, strong) Message2TableViewController *message2Vc;
@property (nonatomic, strong) Message2TableViewController *message3Vc;
@property (nonatomic, strong) Message2TableViewController *message4Vc;
@property (nonatomic, strong) Message2TableViewController *message5Vc;
@property (nonatomic, strong) Message2TableViewController *message6Vc;

// 滚动视图
@property (nonatomic, strong) NSMutableArray *scrollViewModelArray;
// 图片的array用来传值
@property (nonatomic, strong) NSMutableArray *iconArray;
// 点击滚动视图的必要参数
@property (nonatomic, strong) NSMutableArray *article_id;

// 用来接收collectionViewCell的宽度的
@property (nonatomic, assign) CGFloat size;

// 自定义navigationItem的titleView
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) FMDatabase *db;

@property (nonatomic, strong) UIImageView *animationImageView;

// 没有网络的提示框
@property (nonatomic, strong)  UIView *hint;
@end

@implementation ViewController
#pragma mark ---- 滚动视图的网络请求 ------
- (void)scrollViewLoadData
{
    // 在数据持久化之前要将表里的数据清除 防止反复写入
    [_db executeUpdate:@"DELETE FROM PersonList "];
    
    _scrollViewModelArray = [NSMutableArray array];
    _iconArray = [NSMutableArray array];
    _article_id = [NSMutableArray array];
    
    [RequestManager requestWithUrl:@"http://media.api.thejoyrun.com/slide-list" requestType:RequestTypePost parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"data"];
        for (NSDictionary *dataDic in dataArray) {
            ScrollViewModel *model = [[ScrollViewModel alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_scrollViewModelArray addObject:model];
            [_iconArray addObject:model.cover_img];
            [_article_id addObject:model.article_id];
            
            [_db executeUpdate:@"INSERT INTO PersonList (cover_img, article_id) VALUES (?,?)", model.cover_img, model.article_id];
           
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_animationImageView stopAnimating];
            
            LBView *lbView = [[LBView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KWIDTH * 360 / 750)];
            UIView *scView = [lbView addScrollView:CGRectMake(0, 0, KWIDTH, KWIDTH * 360 / 750) iconArray:_iconArray];
            lbView.array = _article_id;
            lbView.nav = self.navigationController;
            
            _message1Vc.tableView.tableHeaderView = scView;
            [_scrollView addSubview:_message1Vc.view];

            [self addNav];
        });
        
    } error:^(NSError *error) {
        
        [_animationImageView stopAnimating];
        [self addHint];
        NSLog(@"错误");
    }];
}

#pragma mark ---- 添加子视图控制器的方法 ------

- (void)creatChildViewController
{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64 + 30, KWIDTH, KHEIGHT - 64 - 30 - 5 )];
    self.scrollView.contentSize = CGSizeMake(KWIDTH * _titleArray.count, KHEIGHT - 64 - 30 - 49);
    self.scrollView.contentOffset = CGPointMake(0, 0);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces= NO;
    
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    // 创建推荐视图控制器对象
    // 将控制器的view加给self.view
    
    // 第一个界面
    _message1Vc = [[Message1TableViewController alloc]init];
    _message1Vc.view.frame = CGRectMake(0, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    
    // 第二个界面
    _message2Vc = [[Message2TableViewController alloc]init];
    _message2Vc.view.frame = CGRectMake(KWIDTH, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    [_message2Vc setSubject_id:1];
    [_scrollView addSubview:_message2Vc.view];
    
    // 第三个界面
    _message3Vc = [[Message2TableViewController alloc]init];
    _message3Vc.view.frame = CGRectMake(KWIDTH * 2, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    [_message3Vc setSubject_id:2];
    [_scrollView addSubview:_message3Vc.view];
    
    // 第四个界面
    _message4Vc = [[Message2TableViewController alloc]init];
    _message4Vc.view.frame = CGRectMake(KWIDTH * 3, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    [_message4Vc setSubject_id:3];
    [_scrollView addSubview:_message4Vc.view];
    
    // 第五个界面
    _message5Vc = [[Message2TableViewController alloc]init];
    _message5Vc.view.frame = CGRectMake(KWIDTH * 4, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    [_message5Vc setSubject_id:4];
    [_scrollView addSubview:_message5Vc.view];
    
    // 第六个界面
    _message6Vc = [[Message2TableViewController alloc]init];
    _message6Vc.view.frame = CGRectMake(KWIDTH * 5, 0, KWIDTH, KHEIGHT - 64 - 30 - 5);
    [_message6Vc setSubject_id:5];
    [_scrollView addSubview:_message6Vc.view];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
        
    // 自定义标题
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 76, 30)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
//    titleLabel.backgroundColor = [UIColor blueColor];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont systemFontOfSize:17];

    self.navigationItem.titleView = _titleLabel;

    self.automaticallyAdjustsScrollViewInsets = NO;

   self.titleArray = @[@"推荐", @"赛事资讯", @"跑步装备", @"提高训练", @"跑步故事", @"跑步文化"];
    // 创建集合视图
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    // 布局 横向滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, 30) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor blackColor];
    // 关闭横向滚动条
    _collectionView.showsHorizontalScrollIndicator = NO;
    // 设置代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    // 注册cell
    [_collectionView registerClass:[MessageCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    // 创建移动的view
    self.moveView = [[UIView alloc]init];
    self.moveView.backgroundColor = [UIColor orangeColor];

    [_collectionView addSubview:_moveView];
    
    [self.view addSubview:_collectionView];

    
    // 添加子视图
     [self creatChildViewController];
    
    
    
    // 判断有没有网络
    if ([[NetWorkState shareInstance]reachability]) {
        // 正在加载的动画
        [self addLoadingHint];

        // 滚动视图的网络请求
        [self scrollViewLoadData];
    } else {
        [self NoNetwork];
        [self addHint];
    }
}

#pragma mark  ---- 存数据库 ----
- (void)NoNetwork
{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"ScrollView.db"];
    
    _db = [FMDatabase databaseWithPath:path];
//    NSLog(@"____%@", path);
    if (![_db open]) {
        NSLog(@"不能打开数据库");
    }
    [_db executeUpdate:@"CREATE TABLE PersonList (cover_img text, article_id text)"];
    
    _iconArray = [NSMutableArray array];
    _article_id = [NSMutableArray array];
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM PersonList"];
    while ([rs next]) {
        NSString *cover_img = [rs stringForColumn:@"cover_img"];
        NSString *article_id = [rs stringForColumn:@"article_id"];
        ScrollViewModel *model = [[ScrollViewModel alloc]init];
        model.cover_img = cover_img;
        model.article_id = article_id;
        [_iconArray addObject:model.cover_img];
        [_article_id addObject:model.article_id];
    }
    [rs close];
    if (_iconArray.count != 0) {
        LBView *lbView = [[LBView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KWIDTH * 360 / 750)];
        UIView *scView = [lbView addScrollView:CGRectMake(0, 0, KWIDTH, KWIDTH * 360 / 750) iconArray:_iconArray];
        lbView.array = _article_id;
        lbView.nav = self.navigationController;
        _message1Vc.tableView.tableHeaderView = scView;
        [_scrollView addSubview:_message1Vc.view];

    }
    [self addNav];
    
}

#pragma mark  ----- nav = self.navigationController ---
- (void)addNav
{
    _message1Vc.nav = self.navigationController;
    _message2Vc.nav = self.navigationController;
    _message3Vc.nav = self.navigationController;
    _message4Vc.nav = self.navigationController;
    _message5Vc.nav = self.navigationController;
    _message6Vc.nav = self.navigationController;
}

#pragma mark  --- 正在加载的时候的动画 -----
- (void)addLoadingHint
{
    _animationImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KWIDTH / 3, KHEIGHT / 2 - KHEIGHT / 15, KWIDTH / 3, KHEIGHT / 15 * 2)];
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 0; i<= 7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loaded_%02d.png", i]];
        [imageArray addObject:image];
    }
    _animationImageView.animationImages = imageArray;
    _animationImageView.animationDuration = 0.1 * imageArray.count;
    _animationImageView.animationRepeatCount = FLT_MAX;
    [_animationImageView startAnimating];
    [self.view addSubview:_animationImageView];
}
#pragma mark ---- 没有网络的提示框 ----
- (void)addHint
{
    // 没有网络的提示框
    _hint = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH / 4, KHEIGHT / 2 - KHEIGHT / 15, KWIDTH / 2, KHEIGHT / 15 * 2)];
    _hint.backgroundColor = [UIColor blackColor];
    _hint.alpha = 0.7;
    _hint.layer.cornerRadius = 10;
    [self.view addSubview:_hint];
    
    UIImageView *noNetworkimageView = [[UIImageView alloc]initWithFrame:CGRectMake(_hint.frame.size.width / 3 + 3, 0, _hint.frame.size.width / 3 + 3, _hint.frame.size.width / 3 * 53 / 63)];
    noNetworkimageView.image = [UIImage imageNamed:@"noNetwork"];
    [_hint addSubview:noNetworkimageView];
    
    UILabel *hintLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, _hint.frame.size.height / 2, KWIDTH / 2, _hint.frame.size.height / 2)];
    hintLabel.text = @"网络超时";
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    [_hint addSubview:hintLabel];
    
    [self performSelector:@selector(removeHint) withObject:nil afterDelay:3];
    
}

- (void)removeHint
{
    [_hint removeFromSuperview];
}

#pragma mark --- 视图将要出现的时候 -----
- (void)viewWillAppear:(BOOL)animated
{
    _titleLabel.text = @"Enjoy!Run";

    [self performSelector:@selector(animation1) withObject:nil afterDelay:3];
     self.navigationController.tabBarController.tabBar.hidden = NO;
}

#pragma mark ---- 视图将要结束的时候取消延迟执行方法 ----
- (void)viewWillDisappear:(BOOL)animated
{
    [ViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(animation1) object:nil];
    [ViewController cancelPreviousPerformRequestsWithTarget:self selector:@selector(animation2) object:nil];
}
#pragma mark  ---- 动画 ------
- (void)animation1
{
    [UIView transitionWithView:_titleLabel duration:1 options:UIViewAnimationOptionTransitionFlipFromTop animations:^{
        _titleLabel.text = @"享动";
    } completion:^(BOOL finished) {
        [self performSelector:@selector(animation2) withObject:nil afterDelay:2];
    }];
}

- (void)animation2
{
    [UIView transitionWithView:_titleLabel duration:1 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _titleLabel.text = @"Enjoy!Run";
    } completion:nil];
}

///////////////////////////////////////////////////////
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.label.text = self.titleArray[indexPath.row];
//    cell.backgroundColor = [UIColor redColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (KHEIGHT < 667) {
        _size = KWIDTH / 4.2;
        _moveView.frame = CGRectMake(5, 27, KWIDTH / 4.2 - 10, 1);
        return CGSizeMake(KWIDTH / 4.2, 30);
    }
    else if (KHEIGHT == 667) {
        _size = KWIDTH / 5;
        _moveView.frame = CGRectMake(5, 27, KWIDTH / 5 - 10, 1);
        return CGSizeMake(KWIDTH / 5, 30);
    } else {
        _size = KWIDTH / 5.5;
        _moveView.frame = CGRectMake(5, 27, KWIDTH / 5.5 - 10, 1);
        return CGSizeMake(KWIDTH / 5.5, 30);
    }

}

#pragma mark --- 控制集合视图的行边距 ---
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 4) {
        if (KWIDTH == 375) {
            [_collectionView setContentOffset:CGPointMake(_size * 1, 0) animated:YES];
        }
        
        } else if (indexPath.row == 1) {
            [_collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
        } else if (indexPath.row == 5) {
            if (KWIDTH == 414) {
                [_collectionView setContentOffset:CGPointMake(_size * 1 - KWIDTH / 5.5 / 2, 0) animated:YES];
            }
        } else if (indexPath.row == 0) {
           
                [_collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
            
        }

    _moveView.frame = CGRectMake(_size * indexPath.row + 5, 27, _size - 10, 1);
    [self.scrollView setContentOffset:CGPointMake(KWIDTH * indexPath.row, 0) animated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%f", scrollView.contentOffset.x);


    // 如果不是集合视图(因为UICollectionView继承于UIScrollView,这个方法对于UICollectionView来说 是重写父类方法)
    if (![scrollView isEqual:_collectionView]) {
        if (scrollView.contentOffset.x / KWIDTH == 1) {
            [_collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        if (KWIDTH == 375) {
        if (scrollView.contentOffset.x / KWIDTH == 3 || scrollView.contentOffset.x / KWIDTH == 2) {
            [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 2), 0) animated:YES];
        } else if (scrollView.contentOffset.x / KWIDTH == 5) {
            [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 4), 0) animated:YES];
        }
        } else if (KWIDTH < 375){
            if (scrollView.contentOffset.x / KWIDTH == 3 || scrollView.contentOffset.x / KWIDTH == 2) {
                [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 2), 0) animated:YES];
            } else if (scrollView.contentOffset.x / KWIDTH == 4){
                [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 2) - 15, 0) animated:YES];
            } else if (scrollView.contentOffset.x / KWIDTH == 5){
                [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 3) - 15, 0) animated:YES];
            }

        } else {
            if (scrollView.contentOffset.x / KWIDTH == 4) {
                [_collectionView setContentOffset:CGPointMake(_size * (scrollView.contentOffset.x / KWIDTH - 3) - KWIDTH / 5.5 / 2, 0) animated:YES];
            }
        }
        _moveView.frame = CGRectMake(_size *(scrollView.contentOffset.x / KWIDTH) + 5, 27, _size - 10, 1);
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
